
class NanoNeuron {
    constructor() {
        this.weight = Math.random(); // 初始权重随机化
        this.bias = Math.random(); // 初始偏差随机化
    }

    predict(input) {
        return input * this.weight + this.bias; // 预测输出
    }

    train(inputs, outputs, learningRate, epochs) {
        for (let epoch = 0; epoch < epochs; epoch++) {
            for (let i = 0; i < inputs.length; i++) {
                const input = inputs[i];
                const target = outputs[i];
                const prediction = this.predict(input);
                const error = target - prediction;
                console.log('输入',input,'输出',target,'预测值',prediction,'权重',this.weight,'偏差',this.bias,'误差',error)
                this.weight += error * input * learningRate; // 更新权重
                this.bias += error * learningRate; // 更新偏差
            }
        }
    }
}

// 示例使用
const inputs = [1, 2, 3, 4];
const outputs = [3, 6, 9, 12];
const nanoNeuron = new NanoNeuron(); // 初始权重和偏差随机化
const learningRate = 0.1; // 学习率
const epochs = 10000; // 迭代次数
nanoNeuron.train(inputs, outputs, learningRate, epochs);
console.log(nanoNeuron.predict(111)); // 预测输入为5时的输出值

//线性回归模型 y = wx + b
//损失函数 误差error = target - prediction
//梯度下降法,最小化损失函数